<template>
  <div class="compose">
    <el-card class="box-card distance" shadow="never">
      <div slot="header" class="clearfix" style="text-align: left">
        <span>职员管理</span>
      </div>
      <FormFilter @emtFormLine="emtFormLine" />
    </el-card>
    <div class="filter-opt distance" style="text-align: left; margin: 10px 0">
      <el-button type="primary" class="button" @click="handleApp"
        >添加</el-button
      >
      <el-button type="danger" class="button" @click="delectTable"
        >删除</el-button
      >
    </div>

    <div class="table-item">
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :header-cell-style="tableRowHdBg"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" prop="id" label="id"> </el-table-column>
        <el-table-column align="center" prop="name" label="姓名">
        </el-table-column>
        <el-table-column
          align="center"
          prop="typename"
          label="职员类型"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="sex"
          :formatter="formatRole"
          label="性别"
        >
        </el-table-column>
        <el-table-column align="center" prop="cardid" label="身份证号">
        </el-table-column>
        <el-table-column align="center" prop="mobile" label="手机号">
        </el-table-column>
        <el-table-column align="center" prop="building" label="管理小区">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">

            <el-button type="success" size="mini" @click="updated(scope.row)">修改</el-button>

            <el-button type="danger" size="mini" @click="delect(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block" v-if="tableData.length > 0">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="formInline.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新增职员"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form :model="addQuery" label-width="80px" ref="addQuery">
        <div class="photo-tp">
          <el-form-item label="照片">
            <el-upload
              class="avatar-uploader"
              action="http://estate.eshareedu.cn/estate/api/upload/add"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                style="width: 50px; height: 50px"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div class="up_bottom">
          <div class="up_left">
            <el-form-item label="姓名" size="medium" prop="name">
              <el-input
                v-model="addQuery.name"
                placeholder="姓名"
                class="input"
              ></el-input>
            </el-form-item>
            <el-form-item label="管辖范围" size="medium" prop="state">
              <el-cascader
                placeholder="管辖范围"
                :options="options"
                filterable
                v-model="addQuery.state"
              ></el-cascader>
            </el-form-item>
            <div class="grid-content bg-purple">
              <el-form-item label="职员类型" prop="type">
                <el-select v-model="addQuery.type">
                  <el-option
                    v-for="item in ItemType"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="性别" prop="sex" :formatter="formatRole">
              <el-radio v-model="addQuery.sex" label="1">男</el-radio>
              <el-radio v-model="addQuery.sex" label="2">女</el-radio>
            </el-form-item>
          </div>
          <div class="up_right">
            <el-form-item label="身份证号" size="medium" prop="cardid">
              <el-input
                v-model="addQuery.cardid"
                class="input"
                placeholder="请输入身份证号"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" size="medium" prop="mobile">
              <el-input
                v-model="addQuery.mobile"
                class="input"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="dialog-bd">
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addformData">确 定</el-button>
          </span>
        </div>
      </el-form>
    </el-dialog>
      <el-dialog
      title="修改职员"
      :visible.sync="dialogVisible1"
      :before-close="handleClose1"
       :data="amends"
    >
      <el-form :model="addQuery" :data="amends" label-width="80px" ref="addQuery">
        <div class="photo-tp">
          <el-form-item label="照片">
            <el-upload
              class="avatar-uploader"
              action="http://estate.eshareedu.cn/estate/api/upload/add"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                style="width: 50px; height: 50px"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div class="up_bottom">
          <div class="up_left">
            <el-form-item label="姓名" size="medium" prop="name">
              <el-input
                v-model="addQuery.name"
                placeholder="姓名"
                class="input"
              ></el-input>
            </el-form-item>
            <el-form-item label="管辖范围" size="medium" prop="state">
              <el-cascader
                placeholder="管辖范围"
                :options="options"
                filterable
                v-model="addQuery.state"
              ></el-cascader>
            </el-form-item>
            <div class="grid-content bg-purple">
              <el-form-item label="职员类型" prop="type">
                <el-select v-model="addQuery.type">
                  <el-option
                    v-for="item in ItemType"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="性别" prop="sex" :formatter="formatRole">
              <el-radio v-model="addQuery.sex" label="1">男</el-radio>
              <el-radio v-model="addQuery.sex" label="2">女</el-radio>
            </el-form-item>
          </div>
          <div class="up_right">
            <el-form-item label="身份证号" size="medium" prop="cardid">
              <el-input
                v-model="addQuery.cardid"
                class="input"
                placeholder="请输入身份证号"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" size="medium" prop="mobile">
              <el-input
                v-model="addQuery.mobile"
                class="input"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="dialog-bd">
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible1 = false">取 消</el-button>

            <el-button type="primary" @click="updateformData">确 定</el-button>

            <el-button type="primary" @click="amend">确 定</el-button>
          </span>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
var token = sessionStorage.getItem("token");
import axios from "axios";
import FormFilter from "./../common/FormFilter.vue";
// import { delectTable, addItem } from "../../utils/utils";
import { delectTable, addItem } from "../../utils/utils";

export default {
  components: {
    FormFilter,
  },
  data() {
    return {
      updatedData: [],

      amends: [],

      addQuery: {
        id: 0,
        name: "",
        photo: null,
        type: 2,
        sex: 1,
        mobile: "",
        cardid: "",
        pass: null,
        state: 0,
        building: [],
      },
      input: "",
      radio: "1",
      ItemType: [],
      options: [],
      imageUrl: "",
      query: {
        name: "",
      },
      myHeaders: { Authorization: token },
      dialogVisible: false,
      dialogVisible1: false,
      tableData: [],
      multipleSelection: [],
      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 4,
      formInline: {
        psize: 5,
        page: 1,
      },
      loading: true,
      total: 0,
    };
  },
  mounted() {
    this.onSearch();
    this.onType();
    this.Administer();
  },
  methods: {
    // 修改

    updated(value) {
      this.dialogVisible1 = true;
      let replica = value;
      console.log(replica);
      this.updatedData = replica;
    },
    async updateformData() {
      console.log(this.updatedData);
    },

    async amend(value) {
      this.amends = value;
      this.dialogVisible1 = true;
      console.log(this.amends);
    },
    // 添加

    async addformData(id) {
      let res = await addItem({
        id: this.addQuery.id,
        building: this.addQuery.building,
        cardid: this.addQuery.cardid,
        mobile: this.addQuery.mobile,
        name: this.addQuery.name,
        pass: this.addQuery.pass,
        photo: this.addQuery.photo,
        sex: this.addQuery.sex,
        state: this.addQuery.state,
        type: this.addQuery.type,
        typename: this.addQuery.typename,
      });
      console.log(res);

      if (res.errCode == "10000") {
        this.$message.success("添加成功");
        this.dialogVisible = false;
         this.$refs.addQuery.resetFields()
        this.onSearch();
      } else {
        this.$message.error("添加错误");
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    onType() {
      axios
        .get("http://estate.eshareedu.cn/estate/api/stafftype/list")
        .then((res) => {
          console.log(res.data.data.list);
          const { errCode, data } = res.data;
          if (errCode == "10000") {
            this.ItemType = res.data.data.list;
          }
        });
    },
    async delectTable() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选你删除的数据",
        });
      } else {
        let ids = [];
        this.multipleSelection.forEach((item) => {
          ids.push(item.id);
        });
        let res = await delectTable({
          ids: ids,
        });
        if (res.errCode == "10000") {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.onSearch();
        }
      }
    },
    // 管辖范围
    Administer() {
      axios
        .get("http://estate.eshareedu.cn/estate/api/building/list")
        .then((res) => {
          console.log(typeof JSON.stringify(res.data));
          const { errCode, data } = res.data;
          if (errCode == "10000") {
            this.options = JSON.stringify(data);
          }
          console.log(res.data);
        });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 200 / 200 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    delect(val) {
      const params = {
        Authorization: sessionStorage.getItem("token"),
      };
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .get(
              "http://estate.eshareedu.cn/estate/api/staff/delete?id=" + val,
              { headers: params }
            )
            .then((res) => {
              this.tableData = [];
              this.onSearch();
            });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });

      console.log(val);
    },
    handleClose() {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch(() => {
          this.dialogVisible = false;
        });
    },
    handleClose1() {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch(() => {
          this.dialogVisible1 = false;
        });
    },
    handleApp() {
      this.dialogVisible = true;
    },
    emtFormLine(data) {
      // 合并
      this.formInline = Object.assign(this.formInline, data);
      console.log(this.formInline);
      this.onSearch();
    },
    formatRole: function (row, column) {
      return row.sex == "1" ? "男" : row.sex == "2" ? "女" : "aaa";
    },
    onSearch() {
      axios
        .get("http://estate.eshareedu.cn/estate/api/staff/list", {
          params: this.formInline,
        })
        .then((res) => {
          const { errCode, data, counts } = res.data;
          console.log(res.data);
          if (errCode == "10000") {
            this.tableData = data.list;
            this.loading = false;
            this.total = data.counts;
          }
        });
    },
    handleSizeChange(val) {
      this.formInline.psize = val;
      this.onSearch();
    },
    handleCurrentChange(val) {
      this.formInline.page = val;
      this.onSearch();
    },

    // 表格头第一行上色
    rowClass({ row, rowIndex }) {
      console.log(rowIndex);
      return "background:rgba(242, 242, 242, 1)";
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    tableRowHdBg1({ rowIndex }) {
      console.log(rowIndex);
      if (rowIndex === 0) {
        return "table-hdbg";
      }
    },
    tableRowHdBg({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color:#EBEEF5";
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>
<style lang="less" scoped>
.up_bottom{
  width:100%;
  display: flex;
  justify-content: space-between;
}
.up_right{
   width: 50%;
  flex:1;
}
.input {
  width: 70%;
}
.up_left {
  flex:1
}
.avatar {
  width: 20px;
  height: 20px;
}
.photo-tp {
  height: 50px;
}
.compose {
  padding: 10px;
}
.clearfix {
  color: rgb(31, 111, 209);
  font-size: 16px;
  margin-left: -10px;
}
.distance {
  border: none;
}
.button {
  width: 80px;
}
.table-hd {
  background: #333;
}
.block {
  text-align: center;
  padding-top: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 68px;
  height: 68px;
  line-height: 48px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>